package yxy.game.pm2.command.union;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.rank.RankAreaLevelUnion;

import java.util.Collection;

/** 联盟 联盟等级排行榜 */
@MessageType(proto = Command.UnionLevelRank, classtype = UnionMessage.UnionLevelRankRequest.class)
public class CMD_UnionLevelRank extends Command<UnionMessage.UnionLevelRankRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionMessage.UnionLevelRankRequest request) {
		String playerCode = messageSource.getTag();

		UnionMessage.UnionLevelRankResponse.Builder response = UnionMessage.UnionLevelRankResponse.newBuilder();

//		RankLevelUnion rankUnion = new RankLevelUnion();
		PlayerBean playerBean = PlayerBean.get(playerCode);
		RankAreaLevelUnion rankUnion = RankAreaLevelUnion.get(playerBean.getServerId());

		Collection<RankEntry> top = rankUnion.top(rankUnion.topSize());
		int rank = 0;
		for (RankEntry entry : top) {
			String code = entry.getKey();

			UnionBean union = UnionBean.get(code);
			if (union == null) {
				continue;
			}

			UnionMessage.RankUnion.Builder builder = UnionMessage.RankUnion.newBuilder();
			builder.setRank(++rank);
			builder.setInfo(new UnionHandle().packUnion(union));
			response.addRank(builder);
		}

		{
			UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
			Result result = new UnionHandle().checkPlayerUnion(entry);
			if (!result.equals(Result.UnionIn) || entry.getUnionBean() == null) {
				send(messageSource, response, Result.Success);
				return;
			}
			UnionBean union = entry.getUnionBean();
			int unionrank = 0;
			RankEntry rankentry = rankUnion.get(union.getCode());
			if (rankentry != null) {
				unionrank = rankUnion.rank(union.getCode());
			}

			UnionMessage.RankUnion.Builder builder = UnionMessage.RankUnion.newBuilder();
			builder.setRank(unionrank);
			builder.setInfo(new UnionHandle().packUnion(union));
			response.setMy(builder);
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, UnionMessage.UnionLevelRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}